package org.edu.modules.growth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.growth.config.MathTool;
import org.edu.modules.growth.config.QueryConditionTool;
import org.edu.modules.growth.dto.TeacherDTO;
import org.edu.modules.growth.dto.VeJsczExamDetailDTO;
import org.edu.modules.growth.dto.VeJsczExamLogDTO;
import org.edu.modules.growth.entity.*;
import org.edu.modules.growth.mapper.*;
import org.edu.modules.growth.service.IVeJsczExamService;
import org.edu.modules.growth.vo.QueryCondition;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@AllArgsConstructor
public class VeJsczExamServiceImpl extends ServiceImpl<IVeJsczExamMapper,
        VeJsczExam> implements IVeJsczExamService {

    private IVeJsczExamMapper mExamMapper;

    private IVeJsczExamLogStudentMapper mStudentMapper ;

    private IVeJsczExamLogTeacherMapper mTeacherMapper ;

    private IVeJsczExamLogLeaderMapper mLeaderMapper ;

    private IVeJsczExamLogDetailMapper mLogDetailMapper ;

    private IVeJsczExamStageDetailMapper mStageDetailMapper ;


    @Override
    public Boolean isSubmitStudent(Map<String,Object> map) {
        List<VeJsczExamLogStudent> list =  mStudentMapper.selectByMap(map) ;
        if( !CollectionUtils.isEmpty(list)){
            return true ;
        }
        return false;
    }

    @Override
    public Boolean isSubmitTeacher(Map<String, Object> map) {
        List<VeJsczExamLogTeacher> list =  mTeacherMapper.selectByMap(map) ;
        if( !CollectionUtils.isEmpty(list)){
            return true ;
        }
        return false;
    }

    @Override
    public Boolean isSubmitLeader( QueryWrapper<VeJsczExamLogLeader> wrapper) {
        List<VeJsczExamLogLeader> list =  mLeaderMapper.selectList(wrapper) ;
        if( !CollectionUtils.isEmpty(list)){
            return true ;
        }
        return false;
    }

    @Override
    public int detailNum(Long stageId) {
        Map<String,Object> map = Maps.newHashMap() ;
        map.put("stageId",stageId) ;
        List<VeJsczExamStageDetail> list = mStageDetailMapper.selectByMap(map) ;
        return list == null ? 0 :list.size();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addExamStudent(VeJsczExamLogDTO dto, LoginUser user) {
        Long time = System.currentTimeMillis()/1000 ;
        // 添加锁（按数据锁--未实现）
        synchronized (this) {
            int score = dto.getDetails().stream().mapToInt(VeJsczExamDetailDTO::getScore).sum() ;
            VeJsczExam exam = new VeJsczExam() ;
            // 查询是否有评审记录
            Map<String,Object> map = Maps.newHashMap() ;
            map.put("teacherUserId",dto.getTeachers().get(0).getTeacherUserId()) ;
            map.put("stageId",dto.getStageId()) ;
            List<VeJsczExam> examList =  mExamMapper.selectByMap(map) ;
            if( !CollectionUtils.isEmpty(examList) ){
                VeJsczExam old = examList.get(0) ;
                // 更新操作
                exam.setExamCount(old.getExamCount()+1) ;
                Double all = exam.getStudentAvaScore()*old.getStudentExamTime()+score ;
                exam.setStudentExamTime(old.getStudentExamTime()+1) ;
                exam.setStudentAvaScore(MathTool.divion(all,exam.getStudentExamTime(),2)) ;
                mExamMapper.updateById(exam) ;
            }else {
                TeacherDTO t = dto.getTeachers().get(0) ;
                // 新增操作
                exam.setExamCount(1).setTeacherUserId(t.getTeacherUserId()).setGH(t.getGH()).setXM(t.getXM())
                        .setSemId(dto.getSemId()).setStageId(dto.getStageId()).setStudentExamTime(1)
                        .setStudentAvaScore((double) score).setYearCode(Integer.getInteger(dto.getYearCode()))
                        .setTeacherJyzId(t.getZyzId()) ;
                mExamMapper.insert(exam) ;
            }
            dto.getDetails().forEach(l->{
                VeJsczExamLogDetail detail = new VeJsczExamLogDetail() ;
                detail.setExamId(exam.getId())
                        .setTeacherUserId(dto.getTeachers().get(0).getTeacherUserId())
                .setDetailId(l.getId())
                .setScore(l.getScore());
                mLogDetailMapper.insert(detail) ;
            });
            // 保存学生数据
            VeJsczExamLogStudent log = new VeJsczExamLogStudent() ;
            log.setExamId(exam.getId()).setTerminalId(1L).setStageId(dto.getStageId()).setTeacherUserId(dto.getTeachers()
                    .get(0).getTeacherUserId()).setYearCode(dto.getYearCode()).setCreateTime(time).setKcId(dto.getKcId())
                    .setScore(score).setSemId(dto.getSemId()).setTeacherJyzId(dto.getTeachers().get(0).getZyzId())
                    .setJxbId(dto.getJxbId())
                    .setExamUserId(Long.parseLong(user.getId())) ;
            mStudentMapper.insert(log) ;
        }
    }

    @Override
    public void addExamTeacher(VeJsczExamLogDTO dto, LoginUser user) {
        Long time = System.currentTimeMillis()/1000 ;
        // 添加锁（按数据锁--未实现）
        synchronized (this) {
            int score = dto.getDetails().stream().mapToInt(VeJsczExamDetailDTO::getScore).sum() ;
            VeJsczExam exam = new VeJsczExam() ;
            // 查询是否有评审记录
            Map<String,Object> map = Maps.newHashMap() ;
            map.put("teacherUserId",dto.getTeachers().get(0).getTeacherUserId()) ;
            map.put("stageId",dto.getStageId()) ;
            List<VeJsczExam> examList =  mExamMapper.selectByMap(map) ;
            if( !CollectionUtils.isEmpty(examList) ){
                VeJsczExam old = examList.get(0) ;
                // 更新操作
                exam.setExamCount(old.getExamCount()+1) ;
                Double all = exam.getTeacherAvaScore()*old.getTeacherExamTime()+score ;
                exam.setTeacherExamTime(old.getTeacherExamTime()+1) ;
                exam.setTeacherAvaScore(MathTool.divion(all,exam.getTeacherExamTime(),2)) ;
                mExamMapper.updateById(exam) ;
            }else {
                TeacherDTO t = dto.getTeachers().get(0) ;
                // 新增操作
                exam.setExamCount(1).setTeacherUserId(t.getTeacherUserId()).setGH(t.getGH()).setXM(t.getXM())
                        .setSemId(dto.getSemId()).setStageId(dto.getStageId()).setTeacherExamTime(1)
                        .setTeacherAvaScore((double) score).setYearCode(Integer.getInteger(dto.getYearCode()))
                        .setTeacherJyzId(t.getZyzId()) ;
                mExamMapper.insert(exam) ;
            }
            dto.getDetails().forEach(l->{
                VeJsczExamLogDetail detail = new VeJsczExamLogDetail() ;
                detail.setExamId(exam.getId())
                        .setTeacherUserId(dto.getTeachers().get(0).getTeacherUserId())
                        .setDetailId(l.getId())
                        .setScore(l.getScore());
                mLogDetailMapper.insert(detail) ;
            });
            // 保存学生数据
            VeJsczExamLogTeacher log = new VeJsczExamLogTeacher() ;
            log.setExamId(exam.getId()).setTerminalId(1L).setStageId(dto.getStageId()).setTeacherUserId(dto.getTeachers()
                    .get(0).getTeacherUserId()).setYearCode(dto.getYearCode()).setCreateTime(time)
                    .setScore(score).setSemId(dto.getSemId()).setTeacherJyzId(dto.getTeachers().get(0).getZyzId())
                    .setExamUserId(Long.parseLong(user.getId())) ;
            mTeacherMapper.insert(log) ;
        }

    }

    @Override
    public void addExamLeader(VeJsczExamLogDTO dto, LoginUser user) {
        Long time = System.currentTimeMillis()/1000 ;
        // 添加锁（按数据锁--未实现）
        synchronized (this) {
            int score = dto.getDetails().stream().mapToInt(VeJsczExamDetailDTO::getScore).sum() ;
            List<TeacherDTO> teacherList = dto.getTeachers() ;
            teacherList.forEach(l->{
                VeJsczExam exam = new VeJsczExam() ;
                // 查询是否有评审记录
                Map<String,Object> map = Maps.newHashMap() ;
                map.put("teacherUserId",l.getTeacherUserId()) ;
                map.put("stageId",dto.getStageId()) ;
                List<VeJsczExam> examList =  mExamMapper.selectByMap(map) ;
                if( !CollectionUtils.isEmpty(examList) ){
                    VeJsczExam old = examList.get(0) ;
                    // 更新操作
                    exam.setExamCount(old.getExamCount()+1) ;
                    Double all = exam.getLeaderAvaScore()*old.getLeaderExamTime()+score ;
                    exam.setLeaderExamTime(old.getLeaderExamTime()+1) ;
                    exam.setLeaderAvaScore(MathTool.divion(all,exam.getLeaderExamTime(),2)) ;
                    mExamMapper.updateById(exam) ;
                }else {
                    // 新增操作
                    exam.setExamCount(1).setTeacherUserId(l.getTeacherUserId()).setGH(l.getGH()).setXM(l.getXM())
                            .setSemId(dto.getSemId()).setStageId(dto.getStageId()).setTeacherExamTime(1)
                            .setTeacherAvaScore((double) score).setYearCode(Integer.getInteger(dto.getYearCode()))
                            .setTeacherJyzId(l.getZyzId()) ;
                    mExamMapper.insert(exam) ;
                }
                dto.getDetails().forEach(n->{
                    VeJsczExamLogDetail detail = new VeJsczExamLogDetail() ;
                    detail.setExamId(exam.getId())
                            .setTeacherUserId(l.getTeacherUserId())
                            .setDetailId(n.getId())
                            .setScore(n.getScore());
                    mLogDetailMapper.insert(detail) ;
                });
                // 保存数据
                VeJsczExamLogLeader log = new VeJsczExamLogLeader() ;
                log.setExamId(exam.getId()).setTerminalId(1L).setStageId(dto.getStageId())
                        .setTeacherUserId(l.getTeacherUserId()).setYearCode(dto.getYearCode()).setCreateTime(time)
                        .setScore(score).setSemId(dto.getSemId()).setTeacherJyzId(l.getZyzId())
                        .setExamUserId(Long.parseLong(user.getId())) ;
                mLeaderMapper.insert(log) ;
            });

        }

    }


    @Override
    public Map<String,Object> selectPage(QueryCondition queryCondition ){
        HashMap<String,Object> map = new HashMap<>();
        IPage<VeJsczExam> page = new Page<>(queryCondition.getCurrent(), queryCondition.getPageSize());
        //创建查询的条件
        QueryWrapper<VeJsczExam> wrapper = new QueryWrapper<>() ;
        QueryConditionTool.advancedQueryPage(queryCondition.getConditions(),wrapper);
        wrapper.orderByAsc("listSort");
        page = mExamMapper.selectPage(page,wrapper);
        List<VeJsczExam> list = page.getRecords();
        Integer count = mExamMapper.selectCount(wrapper);
        map.put("list",list);
        map.put("count", count);
        return map;
    }




}
